package com.fwj.ajax;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CrossFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        String origin = request.getHeader("Origin");
        if(org.springframework.util.StringUtils.isEmpty(origin)){
            //允许所有的远程请求
            response.addHeader("Access-Control-Allow-Origin", "*");
        }
        String headers = request.getHeader("Access-Control-Request-Headers");
        if(org.springframework.util.StringUtils.isEmpty(headers)) {
            //允许自定义头，网页可以请求各种内容类型
            response.addHeader("Access-Control-Allow-Headers",headers);
        }
         //允许所有的请求方式
        response.addHeader("Access-Control-Allow-Methods", "*");
        //允许OPTIONS预检命令缓存3600秒
        response.addHeader("Access-Control-Max-Age","3600");
        //使Cookie生效
        response.addHeader("Access-Control-Allow-Credentials","true");
        //放行
        filterChain.doFilter(servletRequest, response);
    }

    @Override
    public void destroy() {

    }
}
